#include "common.h"
#include "mesh.h"

using namespace std;
using namespace cg;

///////////////////////////////////////////////////////////////////////////////
// mesh
///////////////////////////////////////////////////////////////////////////////

Mesh::Mesh( void )
{	
	this->vertices = NULL;
	this->indices = NULL;
	normals = NULL;
	tcoords = NULL;
	this->indicesNum = 0;	
	this->verticesNum = 0;
	SetAuxInfo( false );
}

Mesh::Mesh( float* vertices, int verticesNum, int* indices, int indicesNum )
{
	this->vertices = vertices;
	this->indices = indices;
	this->indicesNum = indicesNum;	
	this->verticesNum = verticesNum;
	//
	normals = NULL;
	tcoords = NULL;
	SetAuxInfo( false );
}

Mesh::~Mesh()
{
	delete [] normals;
	delete [] tcoords;
	delete [] vertices;
	delete [] indices;
}

void Mesh::Render( void )
{	
	assert( normals );
	assert( tcoords );	
	 
	glBegin( GL_TRIANGLES );
	for( int i = 0; i < indicesNum; ++i ) {

		int index = indices[ i ] * 3;
		int indexCoords = indices[ i ] * 2;
	   
		glTexCoord2fv( &tcoords[ indexCoords ] );		
		glNormal3fv( &normals[ index ] );
		glVertex3fv( &vertices[ index ] );		
	}
	glEnd();	

	if ( auxInfo ) {
		glBegin( GL_LINES );
		for( int i = 0; i < verticesNum; ++i ) {
			glColor3f( 0, 0, 1 );
			int index = i * 3;
			glVertex3fv( &vertices[ index ] );
			Vec3 temp = Vec3( &vertices[ index ] ) + Vec3( &normals[ index ] ) * 0.05f;			
			glVertex3fv( temp.toFloat() );
		}
		glEnd();		
	}	
}

///////////////////////////////////////////////////////////////////////////////
// Quad
///////////////////////////////////////////////////////////////////////////////

void Quad::Render( void )
{	
	glBegin( GL_QUADS );
	glNormal3fv( normal.toFloat() );
	for( int i = 0; i < 4; ++i ) {		
		glTexCoord2fv( textCoords[ i ].toFloat() );		
		glVertex3fv( vertices[ i ].toFloat() );		
	}
	glEnd();	
}